import router from '@/router'
import { accountLogin, findUserById, findUserMenu } from '@/service/login'
import { IAccount } from '@/service/login/types'
import ls from '@/utils/cache'
import mapMenus from '@/utils/map-menus'
import { ElMessage } from 'element-plus'
import { Module } from 'vuex'
import { IRootState } from '../types'
import { ILoginState } from './types'

const LoginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state () {
    return {
      token: '',
      userInfo: {},
      userMenu: []
    }
  },
  actions: {
    // IAccount 是传入的账号信息的类型
    async accountLoginAction ({ commit }, payload: IAccount) {
      // 1. 登陆
      const loginRes = await accountLogin(payload)
      console.dir(loginRes)
      if (loginRes.response?.status === 400) {
        ElMessage({
          message: loginRes.response.data,
          grouping: true,
          type: 'error'
        })
        return false
      } else {
        const { id, token } = loginRes.data
        commit('setToken', token)
        ls.setCache('token', token)
        // 2. 查询用户信息
        const userInfoRes = await findUserById(id)
        commit('setUserInfo', userInfoRes.data)
        ls.setCache('userInfo', userInfoRes.data)
        const menuRes = await findUserMenu(id)
        commit('setUserMenu', menuRes.data)
        ls.setCache('userMenu', menuRes.data)
        // 跳转首页
        router.push('/main')
        return true
      }
    },

    // 刷新时候每次执行
    initState ({ commit }) {
      const token = ls.getCache('token')
      if (token) {
        commit('setToken', token)
      }
      const userInfo = ls.getCache('userInfo')
      if (userInfo) {
        commit('setUserInfo', userInfo)
      }
      const userMenu = ls.getCache('userMenu')
      if (userMenu) {
        commit('setUserMenu', userMenu)
      }
    }
  },
  mutations: {
    setToken (state, token: string) {
      state.token = token
    },
    setUserInfo (state, userInfo) {
      state.userInfo = userInfo
    },
    setUserMenu (state, userMenu) {
      state.userMenu = userMenu
      // 根据菜单添加动态路由
      const routes = mapMenus(userMenu)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })
    }
  }
}

export default LoginModule
